"""
    对接容联云短信平台接口
"""

import time
import hashlib
import requests
import base64
import random

from django_redis import get_redis_connection
from django.http import JsonResponse


class YunTongXunAPI:
    def __init__(self,account_sid,auth_token,app_id,template_id):
        self.account_sid = account_sid
        self.auth_token = auth_token
        self.app_id = app_id
        self.template_id = template_id

    def get_url(self):
        """
        https://app.cloopen.com:8883/2013-12-26/Accounts
        /{account_sid}/SMS/TemplateSMS?sig={}
        """
        time_str = time.strftime("%Y%m%d%H%M%S")
        md5 = hashlib.md5()
        md5.update((self.account_sid+self.auth_token+time_str).encode())
        sig_url = md5.hexdigest().upper()

        return f"https://app.cloopen.com:8883/2013-12-26/Accounts/{self.account_sid}/SMS/TemplateSMS?sig={sig_url}"

    def get_headers(self):
        time_str = time.strftime("%Y%m%d%H%M%S")
        base_str = self.account_sid + ':'+ time_str
        authorization = base64.b64encode(base_str.encode()).decode()
        headers= {
        "Accept": "application/json",
        "Content-Type": "application/json;charset=utf-8;",
        "Authorization":authorization}
        return headers

    def get_body(self,phone,code):
        data = {
        "to":phone,
        "appId":self.app_id,
        "templateId":self.template_id,
        "datas":[code,5]  #code是6位数验证码,时限是五分钟
        }
        return data

    def run(self,phone,code):
        url = self.get_url()
        headers = self.get_headers()
        body = self.get_body(phone,code)

        # html = requests.post(url=url,headers=headers,data=json.dumps(body)).text
        html = requests.post(url=url,headers=headers,json=body).json()
        print(html)

if __name__ == '__main__':
    config = {
    "account_sid": "8aaf07087e32a3d9017f209272a100ae",
    "auth_token": "c5538ef509f742339a9f804d1eb7c06a",
    "app_id" : "8aaf07087e32a3d9017f2092746500b4",
    "template_id" : "1",
    }
    ytx = YunTongXunAPI(**config)#双星字典传参
    code = random.randint(100000,999999)
    phone = "18355502553"
    ytx.run(phone=phone,code=code)
